﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BunnyEater.Common.Extensions
{
    public static class DescriptionExtension
    {

        private static Dictionary<string, string> enumDictionary = new Dictionary<string, string>();

        /// <summary>
        /// 获取枚举值描述
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string GetDescription(this System.Enum data)
        {
            var enumType = data.GetType();
            string enumValue = data.ToString();
            var filed = enumType.GetField(enumValue);

            string dictionaryKey = CombinationEnumKey(enumType.Name, enumValue);
            if (enumDictionary.ContainsKey(dictionaryKey))
            {
                return enumDictionary[dictionaryKey];
            }

            if (filed == null)
            {
                return string.Empty;
            }

            string result = string.Empty;

            var descriptionAttribute = filed.GetCustomAttribute<DescriptionAttribute>();
            if (descriptionAttribute == null)
            {
                return result;
            }
            else
            {
                result = descriptionAttribute.Description;
                enumDictionary.Add(dictionaryKey, result);
            }

            return result;
        }

        private static string CombinationEnumKey(params string[] strArr) => string.Join(".", strArr);

    }
}
